<?php

namespace app\api\controller\pc;

use app\services\BaseServices;
use app\services\other\UploadService;
use app\services\system\attachment\SystemAttachmentCategoryServices;
use app\services\system\attachment\SystemAttachmentServices;
use think\cache\driver\Redis;
use think\Exception;
use think\exception\Handle;
use think\facade\Cache;
use app\Request;
use app\services\sms\SmsService;
use crmeb\exceptions\ApiException;
use xin\helper\Str;
use crmeb\services\pay\Pay;

use FormBuilder\Factory\Iview as Form;

//use crmeb\services\FormBuilder as Form;

class TestController extends BaseServices
{
    public function sendSms(Request $request, SmsService $service)
    {

//        $this->dao->sql();
//        dump_sql();

//        dd(app()->make(\app\api\controller\pc\TestController::class));

//        return app('json')->success(410006, []);
//        return app('json')->fail(410003, []);
//        throw new ApiException(410018);

//        list($mobile, $real_name) = $request->postMore([
//            ['mobile', ''],
//            ['real_name', ''],
//        ], true);

//        $where = $request->getMore([
//            [['sid', 'd'], 0],
//            ['keyword', '', '', 'store_name'], // store_name 设置数据库查询字段
//            [['news', 'd'], 0, '', 'is_new'],
//            [['type', 0], 0],
//        ]);

        $res = $request->postMore([['mobile', '']]);
        $service->send($res['mobile'], Str::random(6, 0));
        return app('json')->success(410006, []);
    }

    // 资源存储定义  类别存储位置/日期/文件
    public function upload(Request $request, SystemAttachmentServices $services, SystemAttachmentCategoryServices $cateServices)
    {
        $data = $request->postMore([
            ['filename', 'file'],
            ['type', 1],
        ]);

        if (!$data['filename']) return app('json')->fail(100100);
        // 限制某个id一天上传文件的次数
        $upload = UploadService::init();
        $uploadConf = UploadService::uploadConf();

        if (Cache::has('start_uploads_' . $request->uid()) && Cache::get('start_uploads_' . $request->uid()) >= $uploadConf['max_times']) return app('json')->fail(100101);

        // 设置上传路径  storage_location  新增字段
        $storages = $cateServices->getColumn([], 'storage_location', 'id');
        $path = (empty($storages[$data['type']]) ? 'default' : $storages[$data['type']]) . '/' . date('Y-m-d');
        $info = $upload->to($path)->validate()->move($data['filename']);
        if ($info === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $services->attachmentAdd($res['name'], $res['size'], $res['type'], $res['dir'], $res['thumb_path'], 1, (int)sys_config('upload_type', 1), $res['time'], 3);
        if (Cache::has('start_uploads_' . $request->uid()))
            $start_uploads = (int)Cache::get('start_uploads_' . $request->uid());
        else
            $start_uploads = 0;
        $start_uploads++;
        Cache::set('start_uploads_' . $request->uid(), $start_uploads, 86400);
        $res['dir'] = path_to_url($res['dir']);
        if (strpos($res['dir'], 'http') === false) $res['dir'] = $request->domain() . $res['dir'];
        return app('json')->success(100009, ['name' => $res['name'], 'url' => $res['dir']]);
    }

    public function testform(array $formData = [])
    {
        $field[] = Form::input('menu_name', '按钮名称', $formData['menu_name'] ?? '')->required('按钮名称必填');
        $field[] = Form::input('menu_path', '路由名称', $formData['menu_path'] ?? '')->placeholder('请输入前台跳转路由地址')->required('请填写前台路由地址');
        $params = $formData['params'] ?? '';
        $field[] = Form::input('params', '参数', is_array($params) ? '' : $params)->placeholder('举例:a/123/b/234');
        $field[] = Form::number('sort', '排序', (int)($formData['sort'] ?? 0));
        $field[] = Form::radio('is_show_path', '是否为前端隐藏菜单', $formData['is_show_path'] ?? 0)->options([['value' => 1, 'label' => '是'], ['value' => 0, 'label' => '否']]);

        return app('json')->success(create_form('添加权限', $field, $this->url('/setting/save'), 'POST'));
    }

    public function pay()
    {
        $pay = app()->make(Pay::class, ['quickn_pay']);
        $res = $pay->create("INV01", 2.00, '', '', '');
        dd($res);
    }

    public function antiFake(Request $request)
    {
        list($code) = $request->postMore([
            ['code', 0],
        ], true);

        $url = 'https://Anti.fwdby.com/Mobile/AntiCodeQueryFunc';
        $params = [
            'Code' => 'A1FISCQH3424DB',
            'IP' => '47.250.13.209',
            'Key' => '0a6bb4abc41d8a37',
        ];

        // $quey_param = http_build_query($params);
        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->request('GET', $url, ['query' => $params, 'verify' => false]);
            $res = json_decode($response->getBody()->getContents(), true);
        } catch (\GuzzleHttp\Exception\ServerException $e) {
            dd('ServerException：' . $e->getMessage());
        } catch (\GuzzleHttp\Exception\ClientException $e) {
            dd('ClientException：' . $e->getMessage());
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            dd('RequestException：' . $e->getMessage());
        } catch (\Exception $e) {
            dd('Exception：' . $e->getMessage());
        }

        if (!$res['Success']) return app('json')->fail('产品校验失败：' . $res['ErrorMsg'], []);

        $ret = json_decode($res['Data'], true);
        if ($ret['IndexCode'] == $code) {
            return app('json')->success('产品校验成功', $ret);
        }

        return app('json')->fail('产品校验失败', []);
    }

    public function history(Request $request)
    {
        list($searchWord) = $request->postMore([
            ['searchWord', ''],
        ], true);

        $redisConfigMap = redis_config_map('search_history_type');
        $cacheKey = $redisConfigMap['prifix'] . $request->uid();
        try {
           //  $redis = Cache::store('redis');
            $redis = get_redis_driver($redisConfigMap['db']);
        } catch (\BadFunctionCallException $e) {
            return app('json')->fail($e->getMessage(), []);
        }

        if ($request->method() === 'GET') {
            $res = $redis->handler()->lrange($cacheKey, 0, -1);
            return app('json')->success('查询成功', $res);
        }

        // 读取的长度
        $len = $redis->llen($cacheKey);
        if ($len >= 5) {
            $redis->rPop($cacheKey);// 移除右侧
            $redis->lPush($cacheKey, $searchWord); // 左侧加入
        } else {
            $redis->lPush($cacheKey, $searchWord);
        }
    }

    public function historyDel(Request $request)
    {
        $redisConfigMap = redis_config_map('search_history_type');
        $cacheKey = $redisConfigMap['prifix'] . $request->uid();
        try {
            $redis = get_redis_driver($redisConfigMap['db']);
        } catch (\BadFunctionCallException $e) {
            return app('json')->fail($e->getMessage(), []);
        }

        $redis->del($cacheKey);
        return app('json')->success('删除成功');
    }
}